package com.dongdong.controller;

import com.dongdong.domain.Result;
import com.dongdong.em.ResultEnum;
import com.dongdong.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("shiroUser")
public class ShiroLoginController {
    @RequestMapping("toLogin")
    public String toLogin() {
        return "/admin/login";
    }

    @RequestMapping("login")
    @ResponseBody
    public Result getLogin(User user) {
        /*
         * 编写shiro 认证操作
         *
         * */
        //获取 Subject
        Subject subject = SecurityUtils.getSubject();
        //封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUname(),user.getPwd());
        //登录方法
        try {
            subject.login(token);
            return Result.buildResult(ResultEnum.SUCCESS);

            //登录成功
        } catch (UnknownAccountException e) {
            //登录失败用户名不存在

            return   Result.buildResult(ResultEnum.ERROR);
        } catch (IncorrectCredentialsException e) {
            //登录失败 密码错误

            return Result.buildResult(ResultEnum.ERROR);
        }
    }

}

